<template>
  <el-autocomplete
    v-if="col.type === 'string' && (col.source || col.pinyin_search)"
    :clearable="true"
    v-bind="col.autocomplete"
    v-model="form[col.key]"
    :fetch-suggestions="(qs, cb) => inputQuerySearch(qs, cb, col)"
  />
  <el-input v-else-if="col.type === 'string'" v-model="form[col.key]" />
  <el-upload
    v-else-if="col.type === 'base64'"
    class="avatar-uploader"
    accept="image/*"
    action=""
    :show-file-list="false"
    :before-upload="(file) => beforeAvatarUpload(file, col)"
  >
    <el-image v-if="form[col.key]" :src="form[col.key]" fit="contain" />
    <el-icon v-else class="avatar-uploader-icon">
      <Icon icon="material-symbols:format-list-bulleted" :size="18" />
    </el-icon>
  </el-upload>
  <el-input
    v-else-if="col.type === 'textarea' || col.type === 'text'"
    type="textarea"
    :rows="col.rows || 10"
    v-model="form[col.key]"
  />
  <el-input
    v-else-if="['number', 'int', 'float'].includes(col.type)"
    type="number"
    v-model="form[col.key]"
  />
  <el-input
    v-else-if="col.type === 'password'"
    type="password"
    show-password
    v-model="form[col.key]"
  />
  <el-select
    v-else-if="col.type === 'enum'"
    filterable
    clearable
    allow-create
    v-model="form[col.key]"
    placeholder="请选择"
  >
    <template v-for="(val, index) in col.values" :key="index">
      <el-option v-if="typeof val === 'object'" :label="val.name" :value="val.key" />
      <el-option v-else :label="val" :value="val" />
    </template>
  </el-select>
  <el-select
    v-else-if="col.type === 'list'"
    filterable
    clearable
    allow-create
    multiple
    collapse-tags
    v-model="form[col.key]"
    placeholder="请选择"
  >
    <template v-for="(val, index) in col.values" :key="index">
      <el-option v-if="typeof val === 'object'" :label="val.name" :value="val.key" />
      <el-option v-else :label="val" :value="val" />
    </template>
  </el-select>
  <el-slider
    v-else-if="col.type === 'range'"
    v-model="form[col.key]"
    :min="col.range[0]"
    :max="col.range[1]"
  />
  <el-date-picker
    v-else-if="col.type === 'datetime'"
    v-model="form[col.key]"
    type="datetime"
    placeholder="选择日期时间"
  />
  <el-checkbox v-else-if="col.type === 'bool'" v-model="form[col.key]" />
  <template v-else-if="col.type === 'file'">
    <template v-if="col.batch_upload && form && col && !form.id">
      <el-button @click="addUploadList"> <Icon icon="material-symbols:add" />新增上传 </el-button>
      <div class="batch-upload" v-for="(up, i) in batchUploadList" :key="i">
        <meta-upload v-model="up.data" :meta="col" @change="(file) => uploadChange(file, col)" />

        <div class="close" @click.stop="removeUploadList(i)"
          ><Icon :size="16" icon="material-symbols:close"
        /></div>
      </div>
    </template>
    <template v-else>
      <meta-upload
        v-if="form && col"
        v-model="form[col.key]"
        :meta="col"
        @change="(file) => uploadChange(file, col)"
      />
    </template>
  </template>
  <el-upload
    v-else-if="col.type === 'fileset'"
    class="upload-attachment multiple"
    action="/api/dataio/input_uploader/upload"
    name="upload_file"
    :data="{ save_dir: 'None', event: 'None' }"
    :headers="{ token }"
    multiple
    :limit="10"
    :on-exceed="handleExceed"
    :on-success="(file) => handleSuccess(file, col)"
    :on-remove="(file) => handleRemove(file, col)"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <template #tip>
      <div v-if="col.hint" class="el-upload__tip">
        {{ col.hint }}
      </div>
    </template>
  </el-upload>
</template>

<script>
import MetaUpload from './Upload.vue'
import { getFormValues } from '@/api/basic'
import { useCache } from '@/hooks/web/useCache'
import { ElMessage } from 'element-plus'
import { fileToBase64 } from '@/utils/file'

const { wsCache } = useCache()
export default {
  name: 'MetaForm',
  components: { MetaUpload },
  props: {
    modelValue: {
      type: Object,
      default: () => ({})
    },
    col: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {},
      token: wsCache.get('Admin-Token'),
      batchUploadList: [{ data: {} }]
    }
  },
  computed: {
    form: {
      get: function () {
        return this.modelValue
      },
      set: function (value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  methods: {
    async beforeAvatarUpload(file, col) {
      const base64 = await fileToBase64(file)
      this.form[col.key] = base64
      return false
    },
    handleExceedSingle(files, fileList) {
      this.$message.warning(`当前为单选，请先删除已上传的文件`)
    },
    handleSuccessSingle(res, col) {
      this.form[col.key] = res.file
      this.validateField(col.key)
    },
    handleRemoveSingle(file, col) {
      this.form[col.key] = ''
      this.validateField(col.key)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    handleSuccess(res, col) {
      this.form[col.key] = this.form[col.key] ? this.form[col.key] + ',' + res.file : res.file
      console.log(this.form[col.key])
      this.validateField(col.key)
    },
    handleRemove(res, col) {
      const val = this.form[col.key]
      if (val.split(',').length > 1) {
        this.form[col.key] = val.replace(',' + res.response.file, '')
      } else {
        this.form[col.key] = val.replace(res.response.file, '')
      }
      this.validateField(col.key)
    },
    // initRemoteValues() {
    //   const reqFields = this.meta.filter((col) => ['enum', 'list'].includes(col.type) && col.source)
    //   const reqPromise = reqFields.map((col) =>
    //     getFormValues({ source: col.source, keyField: undefined, nameField: undefined })
    //   )
    //   Promise.all(reqPromise).then((res) => {
    //     res.forEach((r, i) => {
    //       reqFields[i].values = r.values
    //     })
    //   })
    // },
    getFileList(col) {
      const url = this.form[col.key] || ''
      if (url) {
        const names = url.split('/')
        return [{ name: names[names.length - 1], url }]
      }
      return []
    },
    addUploadList() {
      this.batchUploadList.push({ data: {} })
    },
    removeUploadList(index) {
      this.batchUploadList.splice(index, 1)
    },
    getBatchList() {
      return this.batchUploadList
    },
    inputQuerySearch(qs, cb, col) {
      let results = []
      if (col.pinyin_search && col._pinyinEngine) {
        results = qs ? col._pinyinEngine.query(qs) : col.values
      } else {
        results = qs ? col.values.filter((x) => `${x.value}`.includes(qs)) : col.values
      }
      cb(results)
    }
  }
}
</script>

<style scoped lang="less">
:deep(.upload-attachment) {
  .el-upload-list {
    flex: 0 0 300px;
  }

  &.multiple {
    width: 300px;
  }

  &.single {
    display: flex;
    align-items: center;
  }
}
:deep(.el-form-item) {
  &.batch-upload {
    .el-form-item__content {
      align-items: flex-start;
      flex-direction: column;
    }
    .batch-upload {
      position: relative;
      display: flex;
      width: 100%;
      align-items: flex-end;
      .close {
        font-size: 16px;
        cursor: pointer;
        background: #ccc;
        color: #fff;
        display: inline-block;
        width: 16px;
        height: 16px;
        line-height: 16px;
        text-align: center;
        border-radius: 100%;
        margin: 10px;
        &:hover {
          background-color: #aaa;
        }
      }
    }
  }
}
</style>
